import os
from django.shortcuts import render, HttpResponse
from app01 import models

from django.conf import settings


def upload_list(request):
    """文件上传"""
    if request.method == 'GET':
        return render(request, 'upload_list.html')

    # 前端加上那个enctype 后变成
    # 'username': ['root']} >
    # print(request.POST)     # 请求体中得到数据
    # # {'avatar': [ < InMemoryUploadedFile: logo.png(image / png) >]}    # 文件对象【文件和文件内容】
    # print(request.FILES)    # 请求发来的文件 {}

    file_object = request.FILES.get('avatar')  # 文件对象
    # print(file_object.name)     # 文件名
    for chunk in file_object.chunks():
        with open('a3.png', mode='wb') as f:
            f.write(chunk)

    # f = open('a2.png', mode='wb')
    # for chunk in file_object.chunks():
    #     f.write(chunk)
    # f.close()

    return HttpResponse('12345')


from django import forms
from app01.utils.bootstrap import BootStrapFrom, BootStrapModelFrom


class UpForm(BootStrapFrom):
    bootstrap_exclude_fields = ['img']

    name = forms.CharField(label='姓名')
    age = forms.IntegerField(label='年龄')
    img = forms.FileField(label='头像')


def upload_form(request):
    """form上传"""
    title = 'Form上传'
    if request.method == 'GET':
        form = UpForm()
        return render(request, 'upload_form.html', {
            'form': form,
            'title': title
        })

    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        print(
            form.cleaned_data)  # {'name': 'Classroom', 'age': 60, 'img': <InMemoryUploadedFile: 特_03.png (image/png)>}
        # 读取到内容，处理（存储）每个字段的数据
        # 1，读取图片内容，写入到文件夹中并获取文件路径
        image_object = form.cleaned_data.get('img')  # 文件对象
        # file_path = f"app01/static/img/{image_object.name}"   # 由于各系统不一样【/】
        file_path = os.path.join('app01', 'static', 'img', image_object.name)  # 文件路径

        # db_file_path = os.path.join('static', 'img', image_object.name)         # 存储数据库的路肩【静态文件
        # media_path = os.path.join(settings.MEDIA_ROOT, image_object.name)         # 存储数据库的路肩【动态文件 【绝对
        media_path = os.path.join('media', image_object.name)  # 存储数据库的路肩【动态文件 【相对

        f = open(media_path, mode='wb')
        for chunk in image_object.chunks():
            f.write(chunk)
        f.close()

        # 2，将图片文件路径存储到数据库中
        models.Boos.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path
        )

        return HttpResponse('成功')
    return render(request, 'upload_form.html', {
        'form': form,
        'title': title
    })


class UpModelForm(BootStrapModelFrom):
    bootstrap_exclude_fields = ['img']

    class Meta:
        model = models.City
        fields = "__all__"


def upload_model_form(request):
    """model_form文件上传"""
    title = "ModelForm文件上传"
    if request.method == 'GET':
        form = UpModelForm()
        return render(request, 'upload_form.html', {
            'form': form,
            'title': title
        })

    form = UpModelForm(data=request.POST, files=request.FILES)
    # app01 / views / city.py
    if form.is_valid():
        # 对于文件操作 自动保存
        # 字段 + 上传的路径写入数据库
        form.save()
        return render(request, 'city_list.html', {
            'form': form,
            'title': title
        })
    return render(request, 'upload_form.html', {
        'form': form,
        'title': title
    })
